#include "model.h"

Model::Model() {
}

Model::Model(QString objectFile) {
    load(objectFile);
}
void Model::load(QString filename) {

    QString filePath("data/");
    filePath.append(filename);
    model = glmReadOBJ(filePath.toLatin1().data());

    if(model->numtexcoords < 1) {
        qWarning() << "Missing UV map.";
    }

    GLMgroup* group;
    group = model->groups;

    while (group) {
        ModelGroup grp;
        for(int i = 0; i < group->numtriangles; i++) {
            ModelTriangle triangle;
            QVector<QVector3D> verts;
            for(int j = 0; j < 3; j++) {
                QVector3D vector(model->vertices[3 * model->triangles[group->triangles[i]].vindices[j] + 0],
                                 model->vertices[3 * model->triangles[group->triangles[i]].vindices[j] + 1],
                                 model->vertices[3 * model->triangles[group->triangles[i]].vindices[j] + 2]);
                verts.append(vector);
            }
            QVector<QVector3D> norms;
            for(int j = 0; j < 3; j++) {
                QVector3D vector(model->normals[3 * model->triangles[group->triangles[i]].nindices[j] + 0],
                                 model->normals[3 * model->triangles[group->triangles[i]].nindices[j] + 1],
                                 model->normals[3 * model->triangles[group->triangles[i]].nindices[j] + 2]);
                norms.append(vector);
            }
            if(model->numtexcoords > 0) {
                QVector<QVector3D> texs;
                for(int j = 0; j < 3; j++) {
                    QVector3D vector(model->texcoords[2 * model->triangles[group->triangles[i]].tindices[j] + 0],
                                     model->texcoords[2 * model->triangles[group->triangles[i]].tindices[j] + 1],
                                     model->texcoords[2 * model->triangles[group->triangles[i]].tindices[j] + 2]);
                    texs.append(vector);
                }
                triangle.texcoords = texs;
            }
            triangle.vertices = verts;
            triangle.normals = norms;
            grp.triangles.append(triangle);
        }
        groups.append(grp);
        group = group->next;
    }

    qDebug() << "loading file";
}

void Model::draw() {
    foreach(ModelGroup grp, groups) {
        qWarning() << " >> " << grp.triangles.size();
        foreach(ModelTriangle triangle, grp.triangles) {
           QVector<QVector3D> v = triangle.vertices;
           QVector<QVector3D> t = triangle.texcoords;

           glBegin(GL_TRIANGLES);
            glTexCoord2f(t.at(0).x(), t.at(0).y()); glVertex3f(v.at(0).x(), v.at(0).y(), v.at(0).z());
            glTexCoord2f(t.at(1).x(), t.at(1).y()); glVertex3f(v.at(1).x(), v.at(1).y(), v.at(1).z());
            glTexCoord2f(t.at(2).x(), t.at(2).y()); glVertex3f(v.at(2).x(), v.at(2).y(), v.at(2).z());
           glEnd();

        }
    }
}
